package testndk.testservice.service;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;

/**
 * 使用信使实现Activity和Service进行通信
 */
public class MessengerService extends Service{
	
	private static final int TIME = 1;
	public static final int TEST = 0;
	private int i = 0;
	private Timer mTimer = null;
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case TEST:
				/** 获取客户端信使*/
				cMessenger = msg.replyTo;
				/** 执行计时器*/
				mTimer.schedule(new MyTimerTask(), 1000,TIME * 1000);
				break;
			default:
				break;
			}
		}
	};

	/** 服务端信使*/
	private Messenger mMessenger = new Messenger(mHandler);
	/** 客户端信使*/
	private Messenger cMessenger = null;


	@Override
	public IBinder onBind(Intent intent) {
		//派遣一个信使到服务端
		return mMessenger.getBinder();
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mTimer = new Timer();
	}
	

	class MyTimerTask extends TimerTask {
		@Override
		public void run() {
			if (i == 100) {
				i = 0;
			}
			try {
				Message message = Message.obtain(null, MessengerService.TEST,i, 0);
				cMessenger.send(message);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			i++;
		}
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
		if(mTimer!=null){
			mTimer.cancel();
			mTimer = null;
		}
	}

}
